package com.tiancheng.trade.payment.controller.api;

import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import com.tiancheng.trade.payment.model.PaymentOrder;
import com.tiancheng.trade.payment.service.PaymentFlowDetailService;
import com.tiancheng.trade.payment.service.PaymentOrderService;
import com.tiancheng.trade.payment.util.ObjectConvertUtil;
import com.tiancheng.trade.payment.vo.api.QueryFlowDetailVO;
import com.tiancheng.trade.payment.vo.api.res.PaymentOrderResVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 查询订单
 */
@RestController
@RequestMapping("/api/order")
@Slf4j
@Validated
public class QueryOrderApiController {

	@Resource
	private PaymentFlowDetailService paymentFlowDetailService;
	@Resource
	private PaymentOrderService paymentOrderService;


	/**
	 * 查询流水明细
	 * @param queryFlowDetailVO
	 * @return
	 */
	@GetMapping("/findFlowDetail")
	public Result findFlowDetail(QueryFlowDetailVO queryFlowDetailVO) {
		PageInfo pageInfo = paymentFlowDetailService.find(queryFlowDetailVO);
		return Result.success(pageInfo);
	}

	/**
	 * 统计商户时间范围内营收总金额
	 * @param merchantCode
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@GetMapping("/totalAmountOfMerchant")
	public Result totalAmountOfMerchant(@RequestParam(value = "merchant_code", required = false) String merchantCode, @RequestParam("start_time") String startTime,
										@RequestParam("end_time") String endTime,
										@RequestParam(value = "payment_channel", required = false) String paymentChannel) {
		return Result.success(paymentOrderService.totalAmountOfMerchant(merchantCode,
				DateTimeUtil.string2LocalDateTime(startTime, "yyyy-MM-dd HH:mm:ss"),
				DateTimeUtil.string2LocalDateTime(endTime, "yyyy-MM-dd HH:mm:ss"), paymentChannel));
	}

	/**
	 * 获取指定流水的信息
	 * @param flowId
	 * @return
	 */
	@GetMapping("/get")
	public Result get(@RequestParam("flow_id") String flowId) {
		PaymentOrder paymentOrder = paymentOrderService.findByPaymentFlowId(flowId);
		BusinessErrorInfoEnum.CHANNEL_NO_FLOW.assertNotNull(paymentOrder);

		PaymentOrderResVO resVO = ObjectConvertUtil.convert(paymentOrder, PaymentOrderResVO.class).get();
		return Result.success(resVO);
	}
}
